package com.ls.mysql.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ls.mysql.dao.NoticeMapper;
import com.ls.mysql.dao.OrderMapper;
import com.ls.mysql.entity.YzMerchUserOrder;
import com.ls.mysql.entity.YzNotice;
import com.ls.mysql.entity.YzUsers;
import com.ls.mysql.service.UserService;
import com.ls.mysql.util.DateUtil;
import com.ls.mysql.util.FileUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Maple.Chen
 * @Description 测试期间的控制器，不含Service
 * @Date 16:50 2020/5/14
 **/
//@RestController
@Controller
@Transactional
public class Controller1 {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping(value = "/test1", method = RequestMethod.GET)
    public String test1() {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from yz_users limit 109,1");
        return list.get(0).toString();
    }

    @RequestMapping(value = "/success", method = RequestMethod.GET)
    public String success(Model model) {
        // thymeleaf:相当于实现了SpringMVC的ModelView,, 跳转到~/resources/templates/success.html
        /*现在往页面内添加一些session数据，用于模拟动态数据显示*/
        YzUsers u1 = new YzUsers();
        u1.setRealname("张三");
        u1.setAge(22);
        YzUsers u2 = new YzUsers();
        u2.setRealname("李四");
        u2.setAge(18);
        YzUsers u3 = new YzUsers();
        u3.setRealname("王五");
        u3.setAge(19);
        List<YzUsers> allStudents = new ArrayList<>();
        allStudents.add(u1);
        allStudents.add(u2);
        allStudents.add(u3);
        model.addAttribute("stus", allStudents);
        // return "redirect:/queryAllCustomers" 重定向
//        ModelAndView mv = new ModelAndView();
//        mv.setViewName("redirect:/queryAllCustomers");
        return "success";
    }

    @ResponseBody
    @RequestMapping(value = "/mybatis1/{id}", method = RequestMethod.GET)
    public String queryOrderById(@PathVariable String id) {
        SqlSession session = sqlSessionFactory.openSession();
        OrderMapper ud = session.getMapper(OrderMapper.class);
        YzMerchUserOrder yo = ud.queryOrderById(id);
        return yo.toString();
    }

    //用户登录成功后到上传文件页面，使用接口对视图数据填充，thymeleaf展示
    @RequestMapping(value = "user/logged", method = RequestMethod.GET)
    public ModelAndView logined() throws IOException {
        SqlSession session = sqlSessionFactory.openSession();
        NoticeMapper mapper = session.getMapper(NoticeMapper.class);
        List<YzNotice> yzNotices = mapper.queryAllNotice();
        // 自己封装
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> tempMap = null;
        for (YzNotice n : yzNotices) {
            tempMap = new HashMap<>();
            tempMap.put("id", n.getId());
            tempMap.put("title", n.getTitle());
            tempMap.put("priority", n.getPriority());
            tempMap.put("postTime", DateUtil.format(n.getPostTime()));
            tempMap.put("path", n.getPath());
            tempMap.put("tenderer", n.getYzUsers().getRealname());
            list.add(tempMap);
        }
        // 视图填充
        ModelAndView mv = new ModelAndView();
        mv.addObject("notices", list);
        mv.setViewName("fileUp.html");
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = "user/file1", method = RequestMethod.POST)
    public JSONObject FileUpload1(@RequestParam("upfile") MultipartFile uploadFile, HttpServletRequest request) throws ParseException {
        JSONObject json = new JSONObject();
        int statusCode = -1;
        String msg = "文件上传失败,请稍后再试";
        if (uploadFile.isEmpty()) {
            msg = "提交失败！未选择文件";
            json.put("statusCode", statusCode);
            json.put("msg", msg);
            return json;
        }
        String title = (request.getParameter("title") != null ? request.getParameter("title") : null);
        if (title == null) {
            msg = "提交失败！标题不可为空";
            json.put("statusCode", statusCode);
            json.put("msg", msg);
            return json;
        }
        String priority = request.getParameter("priority");
        Integer setPriority = null;
        try {
            setPriority = Integer.valueOf(priority);
        } catch (Exception e) {
            e.printStackTrace();
            setPriority = 1;
        }
        // 判断资源路径是否存在，不存在就创建，即在当前工程目录下创建upload文件夹
        FileUtil.createFileOrPath(request, "upload");
        // 获取文件全名
        String fileOldName = uploadFile.getOriginalFilename();
        // 获取文件名前缀
        String filePrefix = FileUtil.getFileNameExcludingEnds(fileOldName);
        // 获取文件后缀
        String fileSuffix = FileUtil.getFileNameEnds(fileOldName);
        // 文件重命名，追加字符: 文件全名_时间.扩展名
        String newFileName;
        try {
            newFileName = filePrefix + "_" + DateUtil.getCurrentTime("yyyyMMddHHmmss") + fileSuffix;
        } catch (ParseException e) {
            e.printStackTrace();
            newFileName = fileOldName;
        }
        // 文件保存（文件流，保存路径＋文件名）
        String savePath = request.getServletContext().getRealPath(File.separator) + "upload" + File.separator + newFileName;
        boolean success = FileUtil.saveFile(uploadFile, savePath);
        // 如果文件上传成功，就把记录写入数据库
        if (success) {
            YzNotice n = new YzNotice();
            n.setTitle(title);
            n.setPath(savePath);
            n.setPriority(setPriority);
            n.setPostTime(DateUtil.getCurrentDateTime());
            YzUsers u = new YzUsers();
            String uid = ((YzUsers) request.getSession().getAttribute("user")).getId();
            u.setId(uid);
            n.setYzUsers(u);
            SqlSession session = sqlSessionFactory.openSession();
            NoticeMapper mapper = session.getMapper(NoticeMapper.class);
            int i = mapper.saveNotice(n);
            if (i > 0) {
                statusCode = 1;
                msg = "文件上传成功";
            }
        }
        json.put("statusCode", statusCode);
        json.put("msg", msg);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "user/filedel/{id}", method = RequestMethod.DELETE)
    public JSONObject FileDelete1(@PathVariable String id) {
        JSONObject json = new JSONObject();
        int statusCode = -1;
        String msg = "文件删除失败,请稍后再试";
        SqlSession session = sqlSessionFactory.openSession();
        NoticeMapper mapper = session.getMapper(NoticeMapper.class);
        // 首先查到文件存储的位置
        YzNotice yzNotice = mapper.queryNoticeById(id);
        String fileStoragePath = yzNotice.getPath();
        //现在可以执行删除记录操作了
        int i = mapper.delNotice(id);
        if (i > 0) {
            // 记录删除之后删除文件
            FileUtil.deleteFile(fileStoragePath);
            statusCode = 1;
            msg = "文件删除成功";
        }
        json.put("statusCode", statusCode);
        json.put("msg", msg);
        return json;
    }

    // 使用ibatis分页插件查询对象
    @ResponseBody
    @RequestMapping(value = "find", method = RequestMethod.POST)
    public Object queryByPageNum(@RequestParam(name = "pageNum", required = false, defaultValue = "1") int pageNum,
                                 @RequestParam(name = "pageSize", required = false, defaultValue = "10") int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<YzUsers> users = userService.findAllUsers();
        /*
            由于使用分页插件的方法包含了级联查询的方法，即@Many或@One
            所以需要在该方法所涉及的所有实体类上标注@JsonIgnoreProperties(value = {"handler"})注解
            以解决序列化报错问题
         */
        //生成分页信息对象
        PageInfo<YzUsers> pageInfo = new PageInfo<>(users);
        return pageInfo;
    }
}
